package com.sicnu.cheer.leaugebar.contacts.fragment;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;

import com.sicnu.cheer.generalmodule.adapter.base.CommonAdapter;
import com.sicnu.cheer.generalmodule.adapter.viewholder.CommonViewHolder;
import com.sicnu.cheer.generalmodule.bean.MyUser;
import com.sicnu.cheer.generalmodule.fragment.base.BaseFragment;
import com.sicnu.cheer.generalmodule.util.UIHelper;
import com.sicnu.cheer.leaugebar.contacts.R;
import com.sicnu.cheer.leaugebar.contacts.activity.UserInfoActivity;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * Created by cheer on 2017/1/23.
 * 常用联系人页
 */

public class FrequentContactsFragment extends BaseFragment {
    public CommonAdapter<MyUser> mAdapter;
    public List<MyUser> userList=new ArrayList<>();
    public LinearLayout noResultLL;
    private GridView gridView;
    private ProgressDialog loadingDialog;

    @Override
    protected int setLayoutResourceId() {
        return R.layout.fragment_frequent_contacts;
    }

    @Override
    protected void initView() {
        super.initView();
        noResultLL = findViewById(R.id.no_data_ll);
        noResultLL.setVisibility(View.GONE);
        gridView =  findViewById(R.id.data_list);
        //API21以上才有效果----第二种方式，比较简便
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            gridView.setNestedScrollingEnabled(true);
        }
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MyUser myUser = userList.get(position);
                Intent intent = new Intent(mActivity, UserInfoActivity.class);
                intent.putExtra("user", myUser);
                startActivity(intent);
            }
        });
        gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                showDialog(userList.get(position));
                return true;
            }
        });
    }
    /**
     * 弹出框进行常用联系人设置
     * @param user
     */
    private void showDialog(final MyUser user) {
        String content="是否删除常用联系人？";
        new AlertDialog.Builder(mActivity)
                .setTitle("提示")
                .setMessage(content)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialog, int which) {
                        dialog.dismiss();
                        loadingDialog.show();
                        MyUser newUser=MyUser.getCurrentUser(mActivity,MyUser.class);
                        BmobRelation relation=new BmobRelation();
                        relation.remove(user);
                        newUser.setFrequentContacts(relation);
                        newUser.update(mActivity, newUser.getObjectId(), new UpdateListener() {
                            @Override
                            public void onSuccess() {
                                loadingDialog.dismiss();
                                userList.remove(user);
                                mAdapter.notifyDataSetChanged();
                                UIHelper.ToastMessage(mActivity,"删除常用联系人成功");
                                if (userList.size()==0){
                                    noResultLL.setVisibility(View.VISIBLE);
                                }
                            }

                            @Override
                            public void onFailure(int i, String s) {
                                loadingDialog.dismiss();
                                UIHelper.ToastMessage(mActivity,"操作失败:"+s);
                            }
                        });
                    }
                })
                .show();

    }
    @Override
    protected void initData(Bundle arguments) {
        super.initData(arguments);
        userList =new ArrayList<>();
        loadingDialog = new ProgressDialog(mActivity);
        loadingDialog.setMessage("加载中...");
       requestDataFromBmob();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        gridView.setAdapter(mAdapter = new CommonAdapter<MyUser>(mActivity, userList,R.layout.item_frequent_contact) {
            @Override
            public void convert(CommonViewHolder helper, MyUser item) {
                helper.setImageByUrl(R.id.contact_head_iv, item.getHeadPic(),R.mipmap.default_pic);
                helper.setText(R.id.contact_name_tv,item.getNick());
            }
        });
    }
    public void requestDataFromBmob(){
        MyUser myUser=MyUser.getCurrentUser(mActivity,MyUser.class);
        BmobQuery<MyUser> query=new BmobQuery<>();
        query.addWhereRelatedTo("frequentContacts",new BmobPointer(myUser));
        query.findObjects(mActivity, new FindListener<MyUser>() {
            @Override
            public void onSuccess(List<MyUser> list) {
                if (list==null||list.size()==0){
                    noResultLL.setVisibility(View.VISIBLE);
                }else {
                    noResultLL.setVisibility(View.GONE);
                    userList.clear();
                    userList.addAll(list);
                    mAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(int i, String s) {
                noResultLL.setVisibility(View.VISIBLE);
            }
        });
    }
}
